<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //

        //记录sql
        if (config('app.debug') && request()->is('api/*')) {
            DB::listen(function ($query) {
                $sql    = str_replace('?', '"' . '%s' . '"', $query->sql);
                $sql    = vsprintf($sql, $query->bindings);
                $sql    = str_replace("\\", "", $sql);
                $action = substr($sql, 0, 6);
                //($action == 'select' || $action == 'update' || $action == 'delete' || $action == "insert")
                $myfile = fopen(storage_path() . "/logs/sql_" . date("Ymd") . ".txt", "a+") or die("Unable to open file!");
                $times = $query->time / 1000;
                $write = "[" . date('Y-m-d H:i:s') . "][use_time: {$times}]" . " {$sql} " . "\n";
                fwrite($myfile, $write);
                //                fwrite($myfile, $sql . "   use_time:" . $query->time . "ms   " . date('Y-m-d H:i:s') . " \n\n");
                fclose($myfile);
            });
        }
    }
}
